package com.fantazy.task;

import com.fantazy.main.Main;
import com.fantazy.model.ApplicationDatas;
import com.fantazy.model.CrawlerURL;
import com.fantazy.util.Exceptions;
import com.fantazy.util.SystemTools;

import javax.swing.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

public class CrawlerWorker extends SwingWorker<HashSet<String>, String> {

	private static Logger logger = Logger.getLogger(CrawlerWorker.class.getName());
	public CrawlerWorker() {
	}
	private String exceptionMsg = null;

	/**
	 * 如果任务需要在完成后使用线程结果更新GUI组件或者做些清理工作，可覆盖done方法来完成它们。
	 * SwingWorker在EDT上激活done方法，因此可以在此方法内安全地和任何GUI组件交互
	 */
	@Override
	protected void done() {
		super.done();
		if (exceptionMsg == null) {
			for (Iterator<String> it = ApplicationDatas.getPics().iterator(); it.hasNext(); ) {
				Main.display.append(it.next());
				Main.display.append(SystemTools.getLineSeparator());
			}
		} else {
			Main.input.setText(exceptionMsg);
		}
	}

	@Override
	protected HashSet<String> doInBackground() {
		String destination = Main.input.getText();
		try {
			HashSet<String> urls = CrawlerURL.fetchURLs(destination, CrawlerURL.TYPE_IMGS);
			ApplicationDatas.setPics(urls);
		} catch (MalformedURLException e) {
			logger.warning(Exceptions.URL_ERROR);
			exceptionMsg = Exceptions.URL_ERROR;
		} catch (IOException e) {
			logger.warning(Exceptions.NETWORK_ERROR);
			exceptionMsg = Exceptions.NETWORK_ERROR;
		}
		logger.info(ApplicationDatas.getPics().size() + " pics crawled.");
		return ApplicationDatas.getPics();
	}

	@Override
	protected void process(List<String> chunks) {
	}
}


